<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :title="title"
    :close-on-click-modal="false"
    width="600px"
    @close="close"
  >
    <!--  html  -->
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" size="small" label-width="110px">
      <el-form-item label="商品条码：" prop="eanCode">
        <el-input v-model="form.eanCode" placeholder="请输入" maxlength="100" show-word-limit />
      </el-form-item>
      <el-form-item label="商品名称：" prop="goodsName">
        <el-input v-model="form.goodsName" :autosize="{ minRows: 3, maxRows: 6 }" type="textarea" placeholder="请输入" maxlength="60" show-word-limit />
      </el-form-item>
      <el-form-item label="商品价格：" prop="goodsPrice">
        <el-input v-model="form.goodsPrice" placeholder="请输入" />
      </el-form-item>
      <el-form-item v-if="mode==='add'" label="门店：" prop="shopList">
        <el-select
          v-model="form.shopList"
          filterable
          multiple
          collapse-tags
          placeholder="可通过名称搜索"
          style="width: 100%"
          @change="(val)=>idsChange(val,'shop')"
        >
          <el-option label="所有门店" value />
          <el-option
            v-for="(item, index) in manageShopList"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button size="small" round @click="hide">取 消</el-button>
      <el-button size="small" round type="primary" @click="handleSubmit('form')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { isNull } from '@/utils'
import { validateCustomTwoDecimal } from '@/utils/validate'
import { saveMarketingGoods, updateMarketingGoods } from '@/api/marketing'

export default {
  data() {
    // 终端名称
    const validateGoodsPrice = (rule, value, callback) => {
      if (isNull(value)) {
        callback(new Error('请输入金额'))
      } else if (!validateCustomTwoDecimal(value, 7)) {
        callback(new Error('请输入0.01~9999999.99范围金额（小数位不超过2位）'))
      } else {
        callback()
      }
    }
    return {
      // 校验字段
      rules: {
        eanCode: [
          {
            required: true,
            message: '请输入商品条码',
            trigger: ['blur', 'change']
          }
        ],
        goodsName: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: ['blur', 'change']
          }
        ],
        shopList: [
          {
            type: 'array',
            required: true,
            message: '请选择门店',
            trigger: ['blur', 'change']
          }
        ],
        goodsPrice: [
          { required: true, validator: validateGoodsPrice, trigger: ['blur', 'change'] }
        ]
      },
      // 配置
      title: '新增商品',
      resolve: null,
      reject: null,
      // 状态
      dialogVisible: false,
      loading: false,
      // 数据
      mode: 'add',
      shopList: [], // 所有门店key
      lastShopIdsArr: [], // 上一次选择
      originalForm: null,
      form: {
        eanCode: null,
        goodsName: null,
        goodsPrice: null,
        shopList: []
      }
    }
  },
  computed: {
    ...mapGetters([
      'manageShopList'
    ])
  },
  watch: {},
  beforeCreate() {
  },
  created() {
  },
  beforeMount() {
  },
  mounted() {

  },
  beforeUpdate() {
  },
  update() {
  },
  activated() {
  },
  deactivated() {
  },
  beforeDestroy() {
  },
  destroyed() {
  },
  methods: {
    // 弹框相关
    open({ mode, row }) {
      this.getIds()
      if (mode === 'edit' && row) {
        this.title = '编辑商品'
        this.mode = 'edit'
        this.originalForm = row
        const params = Object.assign({}, row)
        console.log(params)
        // return
        params.goodsPrice = this.$math.div(params.goodsPrice, 100, 2) // 转化元
        this.form = params
      }
      if (mode === 'add') {
        this.title = '新增商品'
        this.mode = 'add'
      }
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    close() {
      this.loading = false
      this.form = {
        eanCode: null,
        goodsName: null,
        goodsPrice: null,
        shopList: []
      }
      this.mode = 'add'
      this.title = '新增商品'
      this.originalForm = null
      this.$refs.form.resetFields()
    },

    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.mode === 'add') {
            const params = Object.assign({}, this.form)
            if (params.shopList.findIndex(v => v === '') !== -1) {
              params.shopList.splice(params.shopList.findIndex(v => v === ''), 1)
            }
            params.goodsPrice = this.$math.mul(params.goodsPrice, 100, 0) // 转化分;
            this.loading = true
            saveMarketingGoods(params).then(res => {
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.resolve && this.resolve()
              this.hide()
            }).finally(() => {
              this.loading = false
            })
          } if (this.mode === 'edit') {
            const params = Object.assign({}, this.form)
            params.goodsPrice = this.$math.mul(params.goodsPrice, 100, 0) // 转化分;
            if (params.eanCode === this.originalForm.eanCode) {
              delete params.eanCode
            }
            this.loading = true
            updateMarketingGoods(params).then(res => {
              this.$notify({
                title: '成功',
                message: '保存成功',
                type: 'success',
                duration: 2000,
                offset: 40
              })
              this.resolve && this.resolve()
              this.hide()
            }).finally(() => {
              this.loading = false
            })
          }
        }
      })
    },

    /**
     * 数据组
     */
    // 获取所有门店Ids&终端ids&支付方式
    getIds() {
      const shopIds = ['']
      // 门店
      this.manageShopList.forEach((v) => {
        shopIds.push(v.id)
      })
      this.shopList = shopIds
    },
    /**
     * 按钮组
     */
    /**
     * 状态组
     */
    // 多选改变
    idsChange(val, type) {
      let lastIdsType = ''
      let idsType = ''
      switch (type) {
        case 'shop':
          lastIdsType = 'lastShopIdsArr'
          idsType = 'shopList'
          break
      }
      const lastVal = this[lastIdsType]
      if (val.includes('')) {
        this.form[idsType] = this[idsType]
      }
      if (lastVal.includes('') && !val.includes('')) {
        this.form[idsType] = []
      }
      if (lastVal.includes('') && val.includes('')) {
        val.splice(
          val.findIndex((v) => v === ''),
          1
        )
        this.form[idsType] = val
      }
      if (!lastVal.includes('') && !val.includes('')) {
        if (val.length === this[idsType].length - 1) {
          this.form[idsType] = [''].concat(val)
        }
      }
      this[lastIdsType] = this.form[idsType]
    }

    /**
     * 方法组
     */
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

</style>
